//
//  HtmlWebVC.swift
//  d11
//
//  Created by peale on 2018/11/5.
//  Copyright © 2018年 Tech_001. All rights reserved.
//

import UIKit
import JavaScriptCore
class HtmlWebVC: BXBaseVC, UIWebViewDelegate{
    let customScheme = "customredirect"
    let customHttpsScheme = "customredirects"
    
    var webView: UIWebView?
    var htmlDataStr: String?
    var isBackHome :Bool = false
    var isBack : Bool = false
    var isShowRefresh:Bool = true
     var jsContext: JSContext!
    var hostUrl:String?
    @objc override func currentViewControllerShouldPop() -> Bool {
        if(self.webView?.canGoBack)!{
            self.webView?.goBack()
        }else{
            if isBack == false {
                
                let dialogMessage = UIAlertController(title: "提示", message: "确认离开当前页面?", preferredStyle: .alert)
                dialogMessage.view.tintColor = UIColor.black
                
                let ok = UIAlertAction(title: "确定", style: .default, handler: { (action) -> Void in
                    print("确定")
                     self.dismissLoadHUD()
                    if self.isBackHome == true{
                        let vc =  self.navigationController?.viewControllers[1];
                        self.navigationController?.popToViewController(vc!, animated: true)
                    }else{
                        self.navigationController?.popViewController(animated: true)
                    }
                })
                let cancelExit = UIAlertAction(title: "取消", style: .default, handler: { (action) -> Void in
                })
                dialogMessage.addAction(ok)
                dialogMessage.addAction(cancelExit)
                
                self.tabBarController?.present(dialogMessage, animated: true, completion: nil)
            }
        }
        
        return isBack
    }
    
    override func viewDidLoad() {
        let item = UIBarButtonItem(title: "", style: .plain, target: self, action: nil)
        self.navigationItem.backBarButtonItem = item;
        self.webView = UIWebView()
        let topLogo = UIImage(named: "icon_nav_left_logo")
        let titleView = UIView()
        let topLogoView = UIImageView(image: topLogo)
        titleView.addSubview(topLogoView)
        topLogoView.contentMode = .scaleToFill
        topLogoView.frame = CGRect(x: -(137/2), y:-(35/2), width: 137, height: 35)
        navigationItem.titleView = titleView
        let frame = self.view.frame
        webView!.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height - kTabBarBottom - kNavigationBarHeight)
        webView?.scalesPageToFit = true
        if  isShowRefresh {
            let rightItem = UIBarButtonItem(title: "刷新", style: .plain, target: self, action: #selector(self.webViewReload))
            
            let fullScreenButton = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(actionClosePage))
            
            self.navigationItem.rightBarButtonItems = [rightItem, fullScreenButton]
        }else{
            let fullScreenButton = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(actionClosePage))
            fullScreenButton.tintColor = UIColor.white
            
            self.navigationItem.rightBarButtonItem = fullScreenButton
        }
      //  htmlDataStr = "<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script><script src='https://cdnjs.cloudflare.com/ajax/libs/jquery.qrcode/1.0/jquery.qrcode.min.js'></script><script src='https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.1/clipboard.min.js'></script> \(htmlDataStr ?? "")"
        webView!.delegate = self
        webView!.loadHTMLString(self.htmlDataStr!, baseURL: nil)
        self.view.addSubview(webView!)
        
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
        if let app = WebViewApp.getInstance(request.url!) {
            WebViewApp.route(app)
            return false
        }
        
        if request.url?.scheme == self.customScheme {
            let newUrl = URL(string: request.url!.absoluteString.replacingOccurrences(of: self.customScheme, with: "http"))
            UIApplication.shared.openURL(newUrl!)
            return false
        }else if request.url?.scheme == self.customHttpsScheme {
            let newUrl = URL(string: request.url!.absoluteString.replacingOccurrences(of: self.customHttpsScheme, with: "https"))
            UIApplication.shared.openURL(newUrl!)
            return false
        }

        return true
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        if self._loadView != nil {
            self._loadView?.removeFromSuperview()
        }
       self.showLoadHUD(title: "")
    }
    
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        webView.stringByEvaluatingJavaScript(from: "window.open = function (open) { return function  (url, name, features) { var newurl = url.replace('https://','\(self.customHttpsScheme)://'); newurl = newurl.replace('http://','\(self.customScheme)://'); window.location.href = newurl; return window; }; } (window.open);")
        
        
        let defaults = UserDefaults.standard
        
        var mtusername = ""
        if UserHelper.getLoginStatus() {
            mtusername = (defaults.value(forKey: DefaultKey.USER_LOGIN_NAME) as? String)!
        }
        
        webView.stringByEvaluatingJavaScript(from:"javascript: var setIntVal=setInterval(function(){var msnElements = document.getElementsByName('msn'); if(msnElements.length>=1){clearInterval(setIntVal); if(msnElements){for(var i=0;i<msnElements.length;i++){msnElements[i].value='\(mtusername)'}}} var funcHistory = document.getElementById('history');funcHistory.style.overflow='visible';var funcQueue = document.getElementById('queue'); funcQueue.style.display='block';var funcDiv=document.getElementById('funcDiv');funcDiv.style.position='fixed';funcHistory.style.bottom='0px';funcHistory.style.top='0px';funcQueue.style.zIndex=0; } ,500);")
        
   //     webView.stringByEvaluatingJavaScript(from:"document.documentElement.style.webkitUserSelect='none';");
       // webView.stringByEvaluatingJavaScript(from:"document.documentElement.style.webkitTouchCallout='none';");
        /*js调用swift方法开始*/
        // if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
        //window.webkit.messageHandlers.method.postMessage(param);
        self.jsContext = webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as! JSContext
        let model = SwiftJavaScriptModel()
        //  model.controller = self
        model.jsContext = self.jsContext
        self.jsContext.setObject(model, forKeyedSubscript: "ios" as NSCopying & NSObjectProtocol)
        /*js调用swift方法结束*/
        self.dismissLoadHUD()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        self.dismissLoadHUD()
    }
    
    func webViewDismiss(){
        self.dismiss(animated: true, completion: nil)
    }
    
    @objc func webViewReload(){
        self.webView?.reload()
    }
    
    @objc func actionClosePage(){
        let dialogMessage = UIAlertController(title: "提示", message: "确认离开当前页面?", preferredStyle: .alert)
        dialogMessage.view.tintColor = UIColor.black
        
        let ok = UIAlertAction(title: "确定", style: .default, handler: { (action) -> Void in
            if self.isBackHome == true{
                let vc =  self.navigationController?.viewControllers[1];
                self.navigationController?.popToViewController(vc!, animated: true)
            }else{
                self.navigationController?.popViewController(animated: true)
            }
        })
        let cancelExit = UIAlertAction(title: "取消", style: .default, handler: { (action) -> Void in
        })
        dialogMessage.addAction(ok)
        dialogMessage.addAction(cancelExit)
        self.tabBarController?.present(dialogMessage, animated: true, completion: nil)
    }
}
